<template>
  <el-select
    ref="selectRef"
    popper-class="tree-select-popper"
    v-model="selectedLabel"
    placeholder="请选择"
    clearable
    filterable
    @clear="handleClear"
    @visible-change="handleVisibleChange"
    :remote="true"
    :remote-show-suffix="true"
    :remote-method="enumRemoteMethod"
    :loading="isLoading"
  >
    <!-- 自定义下拉内容 -->
    <el-option :value="selectedLabel" disabled style="height: auto; padding: 0; width: 100%">
      <vxe-table
        show-overflow
        ref="treeTableRef"
        :show-header="false"
        :row-config="{ keyField: colProps.keyField, isCurrent: true, isHover: true, height: 30 }"
        height="274"
        :column-config="{ resizable: true }"
        :tree-config="
          colProps.parentField
            ? {
                expandAll: false,
                transform: true,
                rowField: colProps.keyField,
                parentField: colProps.parentField
              }
            : undefined
        "
        :data="filterData"
        :scroll-y="{ enabled: true, gt: 0 }"
        @cell-click="handleCellClick"
      >
        <vxe-column :tree-node="!!colProps.parentField">
          <template #default="{ row }">
            <div class="text">{{ row[colProps.nameField] }}</div>
          </template>
        </vxe-column>
      </vxe-table>
    </el-option>
  </el-select>
</template>

<script setup>
import { ref, watch, nextTick, onMounted, computed } from 'vue'
import { getFormValues, doApi } from '@/api/basic'
import { getTemplateData } from '@/modules/AutoGrid/tool'

const props = defineProps({
  modelValue: {
    type: [String, Number],
    default: ''
  },
  config: {
    type: Object,
    default: () => ({})
  },
  data: {
    type: Array,
    default: () => []
  },
  form: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue'])

const isLoading = ref(false)
let lastQueryParams = ''

const colProps = computed(() => props.config)
const rowData = computed(() => props.form)
// 任意节点都可以被选择，默认false只能选择叶子节点
const checkStrictly = computed(
  () =>
    colProps.value?.['check-strictly'] === undefined || colProps.value?.['check-strictly'] === false
)

const selectRef = ref()
const treeTableRef = ref()
const queryString = ref('')
const selectedLabel = ref('') // 显示的值（label）
const selectedNode = ref(null) // 选中的节点数据
const treeTable = ref(null) // vxe-table 的引用
const treeData = ref(props.data) // 树形数据
const filterData = computed(() =>
  Array.isArray(treeData.value)
    ? treeData.value.filter((item) =>
        `${item[colProps.value.nameField]}`.includes(queryString.value)
      )
    : []
)

function enumRemoteMethod(qs) {
  if (isLoading.value) {
    return
  }
  queryString.value = qs
  const url = colProps.value.url
  if (url) {
    const params = colProps.value.params
      ? getTemplateData(colProps.value.params, rowData.value)
      : {}
    let newQueryStr = JSON.stringify(params)
    if (newQueryStr != lastQueryParams) {
      lastQueryParams = JSON.stringify(params)
      isLoading.value = true
      doApi(url, params, colProps.value.method)
        .then((res) => {
          treeData.value = res.data.map((x) => ({
            ...x,
            id: `${x.id}`,
            parent_id: `${x.parent_id}`
          }))
          console.log('treeData.value==>', treeData.value)
        })
        .finally(() => {
          isLoading.value = false
        })
    }
  } else {
    isLoading.value = true
    getFormValues({
      ...colProps.value,
      keyField: undefined,
      nameField: undefined,
      params: undefined,
      conditions: { ...colProps.value.params, ...colProps.value.conditions }
    })
      .then((res) => {
        treeData.value = res.values
      })
      .finally(() => {
        isLoading.value = false
      })
  }
}

function getDataByIds() {
  const defaultQuery = {
    ids: [props.modelValue].flat()
  }
  const url = colProps.value.url
  if (url) {
    const params = colProps.value.params
      ? Object.keys(colProps.value.params || {}).reduce((t, c) => {
          try {
            const compiled = template(colProps.value.params[c])
            t[c] = compiled(rowData.value)
            return t
          } catch (e) {
            return t
          }
        }, defaultQuery)
      : defaultQuery
    let newQueryStr = JSON.stringify(params)
    if (newQueryStr != lastQueryParams) {
      lastQueryParams = JSON.stringify(params)
      doApi(url, params, colProps.value.method).then((res) => {
        treeData.value = res.data
      })
    }
  } else {
    getFormValues({
      ...colProps.value,
      keyField: undefined,
      nameField: undefined,
      params: undefined,
      conditions: {
        ...colProps.value.params,
        ...colProps.value.conditions,
        ids: [props.modelValue]
      }
    }).then((res) => {
      treeData.value = res.values
    })
  }
}

if (props.modelValue) {
  getDataByIds()
}

// 根据 id 更新选中的 label 和节点
function updateSelectedLabelById(id) {
  if (id) {
    const node = treeData.value.find((x) => `${x[colProps.value.keyField]}` === `${id}`)
    if (node) {
      selectedLabel.value = node[colProps.value.nameField] // 更新选中的 label
      selectedNode.value = node // 保存选中的节点数据
    }
  } else {
    selectedLabel.value = '' // 清空选中的 label
    selectedNode.value = null // 清空选中的节点数据
  }
}

// 初始化时定位到默认选中的节点
function locateDefaultNode() {
  if (props.modelValue) {
    updateSelectedLabelById(props.modelValue) // 根据 id 更新选中的 label 和节点
    nextTick(() => {
      const table = treeTable.value
      if (table && selectedNode.value) {
        table.setTreeExpand(selectedNode.value, true) // 展开父节点
        table.scrollToRow(selectedNode.value) // 滚动到节点
        table.setCurrentRow(selectedNode.value) // 高亮显示节点
      }
    })
  }
}

// 监听 data 的变化
watch(
  () => treeData.value,
  () => {
    // treeData.value = newData // 更新树形数据
    locateDefaultNode() // 重新定位默认节点
  },
  { immediate: true } // 立即执行一次
)

// 监听 modelValue 的变化
watch(
  () => props.modelValue,
  (newValue) => {
    updateSelectedLabelById(newValue) // 根据 id 更新选中的 label 和节点
  }
)

// 处理单元格点击事件
function handleCellClick({ row }) {
  if (!row.isLeaf && checkStrictly.value) {
    treeTableRef.value.toggleTreeExpand(row)
    return false
  }
  selectRef.value.blur()
  selectedLabel.value = row[colProps.value.nameField] // 更新选中的 label
  selectedNode.value = row // 保存选中的节点数据
  emit('update:modelValue', row[colProps.value.keyField]) // 更新 v-model 的值为节点的 id
  const table = treeTable.value
  if (table) {
    table.setCurrentRow(row) // 高亮显示选中的行
  }
}

// 处理清空事件
function handleClear() {
  selectedLabel.value = '' // 清空选中的 label
  selectedNode.value = null // 清空选中的节点数据
  emit('update:modelValue', '') // 清空 v-model 的值
  const table = treeTable.value
  if (table) {
    table.clearCurrentRow() // 取消高亮显示
  }
}

// 处理下拉框显示/隐藏事件
function handleVisibleChange(visible) {
  if (visible && selectedNode.value) {
    // 当下拉框显示时，展开并定位到选中的节点
    nextTick(() => {
      const table = treeTable.value
      if (table) {
        table.setTreeExpand(selectedNode.value, true) // 展开父节点
        table.scrollToRow(selectedNode.value) // 滚动到节点
        table.setCurrentRow(selectedNode.value) // 高亮显示节点
      }
    })
  }
}

// 组件挂载时定位默认节点
onMounted(() => {
  locateDefaultNode()
})
</script>

<style lang="less">
.tree-select-popper {
  .el-select-dropdown__list,
  .el-select-dropdown__item {
    padding: 0;
  }
  .el-select-dropdown.is-multiple .el-select-dropdown__item.is-selected:after {
    display: none;
  }
}
</style>
